package main

import (
	"encoding/json"
	"flag"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"prometheus-sd-nacos/model"
	"prometheus-sd-nacos/service"
	"prometheus-sd-nacos/util"
	"time"
)

const (
	// 配置文件路径
	confPath = "conf/config.json"
)

func init() {
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.Lshortfile)
}

func checkErr(lablel string, err error) {
	if err != nil {
		log.Fatal(lablel, "失败，原因：", err)
	}
}

// 获取配置
func getConfig() model.Config {
	flag.Parse()
	args := flag.Args()
	configPath := confPath
	if len(args) > 0 {
		configPath = args[0]
	}
	configJSON, err := ioutil.ReadFile(configPath)
	checkErr("read config", err)
	config := model.Config{}
	err = json.Unmarshal(configJSON, &config)
	checkErr("read config", err)
	log.Printf("read config success, content:\n%s", util.Struct2String(config))
	return config
}

func main() {
	signalChan := make(chan os.Signal)
	signal.Notify(signalChan, os.Interrupt, os.Kill)
	// get config
	config := getConfig()
	done := make(chan bool)
	ticker := time.NewTicker(time.Duration(config.Interval) * time.Second)
	defer ticker.Stop()
	go func() {
		signal := <-signalChan
		log.Println("terminated by", signal)
		done <- true
	}()
	for {
		select {
		case <-done:
			log.Println("exit!")
			return
		case <-ticker.C:
			log.Printf("execute!")
			service.GenJobConfs(config)
		}
	}
}
